from django.shortcuts import render_to_response
from django.http import Http404
from django.template import RequestContext
from dbsupply.models import *
from dbsupply.forms import * 

def lemma_item(requset, id, action):
    pass

def pos_item(request, id, action):
    pass

# cool ajax features
def items_ajax_verified(request, model, verified):
    models = {'lemma': Lemma,
              'pos': POSCommon}
    if models.get(model, False):
        q = models[model].objects
    else:
        raise Http404
    if verified == 'verified':
        q = q.filter(verified=True).order_by('-created')[:20]
    elif verified == 'unverified':
        q = q.filter(verified=False).order_by('-created')[:20]
    else:
        q = q.all().order_by('-created')[:20]
    return render_to_response('ajax_item_list.html', {'items': q, 'model': model})


def item_ajax_view(request, model, id):
    models = {'lemma': Lemma,
              'pos': POSCommon}
    if models.get(model, False):
        q = models[model].objects
    else:
        raise Http404
    try:
        item_id = int(id)
    except ValueError:
        raise Http404
    
    q = q.get(id=item_id)
    
    return render_to_response('ajax_item_view.html', {'item': q})


def item_ajax_edit(request, model, id):
    models = {'lemma': Lemma,
              'pos': POSCommon}
    if models.get(model, False):
        q = models[model].objects
    else:
        raise Http404
    try:
        item_id = int(id)
    except ValueError:
        raise Http404
    q = q.get(id=item_id)
    # TODO: create better approach to choose form
    if model == 'lemma':
        form = LemmaForm
    else:
        form = POSCommonForm
    if request.method == "POST":
        result_form = form(request.POST)
        if result_form.is_valid():
             result_form.save()
        return render_to_response('ajax_item_view.html', {'item': q})
    else:
        result_form = form(instance=q)
        return render_to_response('ajax_item_edit.html', {'item': q,
                                                          'form': result_form}, 
                                  context_instance = RequestContext(request))
    
def item_ajax_delete(request, model, id):
    models = {'lemma': Lemma,
              'pos': POSCommon}
    if models.get(model, False):
        q = models[model].objects
    else:
        raise Http404
    try:
        item_id = int(id)
    except ValueError:
        raise Http404
    q = q.get(id=item_id)
    
    if request.method == "GET":
        return render_to_response('ajax_item_delete.html', {'item': q,})
    else:
        return render_to_response('ajax_item_delete.html', {'item': None})